//
//  ThemeEditViewController.m
//  DaJiang
//
//  Created by sally on 16/10/6.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "CellManager.h"
#import "FeedbackView.h"
#import "OtherModel.h"
#import "PickerView.h"
#import "ThemeEditViewController.h"

@interface ThemeEditViewController () <UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource,PickerViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIImageView *bgImage;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *userTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *locLabel;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (strong, nonatomic) NSMutableArray *tableData;
@property (strong, nonatomic) UITextField *nameTextField;
@property (strong, nonatomic) UITextField *priceTextField;
@property (strong, nonatomic) UITextField *timeTextField;
@property (strong, nonatomic) NSString *topicName;
@property (strong, nonatomic) NSString *price;
@property (strong, nonatomic) NSString *time;
@property (strong, nonatomic) NSString *desc;
@property (strong, nonatomic) PickerView *timePicker; //时间选择器
@property (strong, nonatomic) NSMutableArray *timeArr;

@end

@implementation ThemeEditViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setNotification];
  [self initControl];
  [self initData];
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 设置通知
- (void)setNotification {
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

#pragma mark 初始化控件
- (void)initControl {
  if (self.themeEditType == ThemeEditType_BecomeExpert) { //成为专家
    self.title = @"成为专家";
    self.headerView.height = GExpertImageHeight;
    [self.sureBtn setTitle:@"提交审核" forState:UIControlStateNormal];

    //装配头控件
    self.bgImage.image = self.headImage;
    self.userNameLabel.text = self.becomeExpertModel.userName;
    self.userTitleLabel.text = self.becomeExpertModel.userTitle;
    self.locLabel.text = self.becomeExpertModel.loc;

  } else { //新增or编辑话题
    self.title = @"话题";
    self.headerView.height = 0;
    [self.sureBtn setTitle:@"编辑" forState:UIControlStateNormal];
  }
  [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}

#pragma mark 初始化数据
- (void)initData {
  self.tableData = [NSMutableArray array];
  self.timeArr = [[NSMutableArray alloc] init];
  [self.tableData addObject:@[ @"话题名称  0-20字", @"" ]];
  [self.tableData addObject:@[ @"话题介绍", @"" ]];
  [self.tableData addObject:@[ @"选择时长" ]];
  [self.tableData addObject:@[ @"话题价格" ]];
  [self initControlText];

  [TimeModel queryTimeWithCompletion:^(NSMutableArray *timeList) {
    if (timeList) {
      [self.timeArr removeAllObjects];
      self.timeArr = timeList;
    } else {
      NSError *error = [TimeModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
  }];
}

#pragma mark 初始化控件数据
- (void)initControlText {
  self.topicName = self.topicModel.data.topic_name;
  self.price = self.topicModel.data.topic_price ? [NSString stringWithFormat:@"%.2f", self.topicModel.data.topic_price] : @"";
  self.time = self.topicModel.data.time_length;
  self.desc = self.topicModel.data.topic_desc;
}

#pragma mark - action
#pragma mark 点击提交审核/编辑
- (IBAction)actionOnSure:(id)sender {
  if (self.themeEditType == ThemeEditType_BecomeExpert) { //成为专家
    if (self.topicName.length < 1) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入话题名称"];
      return;
    }
    if (self.desc.length < 1) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入话题介绍"];
      return;
    }
    if (self.time.length < 1) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入时长"];
      return;
    }
    if (self.price.length < 1) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入话题价格"];
      return;
    }
    if (![OperationManager validateMoney:self.price]) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入正常格式的话题价格"];
      return;
    }
    if ([self.price floatValue] <= 0) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入大于0的话题价格"];
      return;
    }

    FeedbackView *feedbackView = [[FeedbackView alloc] initWithFeedbackType:FeedbackType_Notebook];
    self.becomeExpertModel.topicName = self.topicName;
    self.becomeExpertModel.timeLength = self.time;
    self.becomeExpertModel.topicDesc = self.desc;
    self.becomeExpertModel.topicPrice = [self.price floatValue];
    feedbackView.becomeExpertModel = self.becomeExpertModel;
    feedbackView.idCardImageArr = self.idCardImageArr;
    feedbackView.qualificationImageArr = self.qualificationImageArr;
    feedbackView.headImage = self.headImage;
    [feedbackView show];

  } else { //新增or编辑话题
    if (self.topicName.length < 1) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入话题名称"];
      return;
    }
    if (self.desc.length < 1) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入话题介绍"];
      return;
    }
    if (self.time.length < 1) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入时长"];
      return;
    }
    if (self.price.length < 1) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入话题价格"];
      return;
    }
    if (![OperationManager validateMoney:self.price]) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入正常格式的话题价格"];
      return;
    }
    if ([self.price floatValue] <= 0) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入大于0的话题价格"];
      return;
    }

    NSInteger topicId = self.topicModel.topicid ? self.topicModel.topicid : GTopicIdInit;

    [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];
    [TopicModel addOrUpdateTopicWithTopicId:topicId topicName:self.topicName timeLength:self.time topicDesc:self.desc topicPrice:self.price completion:^(TopicModel *topicModel) {
      if (topicModel) {
        //刷新话题列表数据
        if (self.delegate && [self.delegate respondsToSelector:@selector(refreshThemeListVc)]) {
          [self.delegate refreshThemeListVc];
        }
        [self.navigationController popViewControllerAnimated:YES];
      } else {
        NSError *error = [TopicModel getLastError];
        [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
      }
      [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    }];
  }
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return self.tableData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return [[self.tableData objectAtIndex:section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  //section头部高度
  if ((self.themeEditType == ThemeEditType_Edit || self.themeEditType == ThemeEditType_Add) && section == 0) { //编辑话题的第一行
    return 0.1;
  }
  return GNormalMargin;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
  return 0.1; //section底部高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.section == 1 && indexPath.row == 1) { //第二项
    return GTextViewHeight - NavHeight;
  }
  return NavHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  UITableViewCell *cell;
  if (indexPath.section == 2) {
    //主副标题形式
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    //向右箭头，列表项点击性
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;

    //副标题
    [CellManager configCellDetailText:cell];
    cell.detailTextLabel.text = self.time;

  } else {

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];

    //向右箭头，列表项点击性
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    //编辑行
    if ((indexPath.section == 0 && indexPath.row == 1) || indexPath.section == 2 || indexPath.section == 3) {
      if (indexPath.section == 3) {
        self.priceTextField = [CellManager configCellNormalTextField:cell];
        [cell.contentView addSubview:self.priceTextField];
        self.priceTextField.text = self.price;
      } else if (indexPath.section == 2) {
        self.timeTextField = [CellManager configCellNormalTextField:cell];
        [cell.contentView addSubview:self.timeTextField];
        self.timeTextField.text = self.time;
      } else {
        self.nameTextField = [CellManager configCellTextField:cell type:TextFieldType_Long];
        [cell.contentView addSubview:self.nameTextField];
        self.nameTextField.text = self.topicName;
      }
    }

    //编辑框
    if (indexPath.section == 1 && indexPath.row == 1) { //第二项
      UITextView *textView = [CellManager configCellTextView:cell];
      textView.text = self.desc;
      textView.delegate = self;
      [cell.contentView addSubview:textView];
    }
  }

  //主标题
  [CellManager configCellNormalText:cell];
  cell.textLabel.text = [[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
  if (indexPath.section == 0 && indexPath.row == 0) { //字数限定提示的字体设10
    NSString *text = [[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attrStr addAttribute:NSFontAttributeName value:GFontWithSize(GXSmallFontSize) range:NSMakeRange(6, text.length - 6)];
    cell.textLabel.attributedText = attrStr;
  }

  return cell;
}

#pragma mark TableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; //返回后选中状态消失

  if (indexPath.section == 2) {//时间
    self.timePicker = [[PickerView alloc] initWithPickerType:PickerType_Loc];
    self.timePicker.delegate = self;
    [self.timePicker show];

    //重载cell
    TimeModel *timeModel = self.timeArr[0];
    self.time = [NSString stringWithFormat:@"%@小时", timeModel.data.choose_time];
    [self reloadTimeCell];
  }
}

#pragma mark Picker Data Source Method
// 返回列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
  return 1;
}

// 返回该列行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
  return self.timeArr.count;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
  TimeModel *time = [self.timeArr objectAtIndex:row];
  self.time = [NSString stringWithFormat:@"%@小时", time.data.choose_time];

  //重载cell
  [self reloadTimeCell];
}

#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
  TimeModel *time = [self.timeArr objectAtIndex:row];
  return [NSString stringWithFormat:@"%@小时", time.data.choose_time];
}

#pragma mark PickerViewDelegate
- (void)cancelSelect:(UIView *)picker{
  if (picker == self.timePicker) {
    self.time = self.topicModel.data.time_length;
    [self reloadTimeCell];
  }
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
  self.desc = textView.text;
}

#pragma mark - 私有方法
#pragma mark textfield中的文本发生改变时
- (void)textFieldChanged:(NSNotification *)notification {
  UITextField *textField = (UITextField *) notification.object;
  if ([textField isEqual:self.nameTextField]) {
    self.topicName = textField.text;
  } else if ([textField isEqual:self.priceTextField]) {
    self.price = textField.text;
  } else if ([textField isEqual:self.timeTextField]) {
    self.time = textField.text;
  }
}

#pragma mark 重载时间cell
- (void)reloadTimeCell {
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
  [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
}

@end
